/**
 * @file 笔记服务
 * @description 提供笔记相关的 API 调用（目前使用 Mock 数据，后续可切换到真实 API）
 * @author AI Assistant
 * @version 1.0.0
 * @since 2025-10-30
 */

import type { CreateNoteInput, Note, QueryNoteParams, UpdateNoteInput, User } from '../types'

/**
 * Mock 用户数据
 */
const mockUsers: User[] = [
  { id: 1, name: '张三', avatar: 'https://i.pravatar.cc/150?img=1', email: 'zhangsan@example.com' },
  { id: 2, name: '李四', avatar: 'https://i.pravatar.cc/150?img=2', email: 'lisi@example.com' },
  { id: 3, name: '王五', avatar: 'https://i.pravatar.cc/150?img=3', email: 'wangwu@example.com' },
  { id: 4, name: '赵六', avatar: 'https://i.pravatar.cc/150?img=4', email: 'zhaoliu@example.com' },
  { id: 5, name: '钱七', avatar: 'https://i.pravatar.cc/150?img=5', email: 'qianqi@example.com' }
]

// 安全获取用户（noUncheckedIndexedAccess 下避免 undefined）
const pickUser = (i: number): User => mockUsers[i]!

// 外部联系人（用于模拟 from_user / to_users）
const mockExternalContacts: User[] = [
  {
    id: 20_001,
    name: '王鹏',
    avatar: 'https://i.pravatar.cc/150?img=21',
    email: 'wangpeng@partner.com'
  },
  {
    id: 20_002,
    name: '李娜',
    avatar: 'https://i.pravatar.cc/150?img=22',
    email: 'lina@partner.com'
  },
  {
    id: 20_003,
    name: '陈静',
    avatar: 'https://i.pravatar.cc/150?img=23',
    email: 'chenjing@partner.com'
  },
  {
    id: 20_004,
    name: '赵磊',
    avatar: 'https://i.pravatar.cc/150?img=24',
    email: 'zhaolei@partner.com'
  },
  {
    id: 20_005,
    name: '刘洋',
    avatar: 'https://i.pravatar.cc/150?img=25',
    email: 'liuyang@partner.com'
  },
  {
    id: 20_006,
    name: '高磊',
    avatar: 'https://i.pravatar.cc/150?img=26',
    email: 'gaolei@partner.com'
  },
  {
    id: 20_007,
    name: '宋倩',
    avatar: 'https://i.pravatar.cc/150?img=27',
    email: 'songqian@partner.com'
  },
  {
    id: 20_008,
    name: '杨帆',
    avatar: 'https://i.pravatar.cc/150?img=28',
    email: 'yangfan@partner.com'
  },
  {
    id: 20_009,
    name: '张越',
    avatar: 'https://i.pravatar.cc/150?img=29',
    email: 'zhangyue@partner.com'
  },
  {
    id: 20_010,
    name: '周强',
    avatar: 'https://i.pravatar.cc/150?img=30',
    email: 'zhouqiang@partner.com'
  }
]

// 安全获取外部联系人
const pickExt = (i: number): User => mockExternalContacts[i]!

/**
 * Mock 笔记数据
 */
const mockNotes: Note[] = [
  {
    id: 1,
    type: 'note',
    content:
      '今天完成了客户管理系统的笔记功能设计，包括时间线展示、筛选功能和响应式布局。明天计划开始实现邮件集成功能。',
    images: [
      {
        url: 'https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e?w=1200&q=80&auto=format&fit=crop'
      },
      {
        url: 'https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?w=1200&q=80&auto=format&fit=crop'
      }
    ],

    is_synced: false,
    like_count: 12,
    comment_count: 3,
    created_at: Date.now() - 3_600_000,
    updated_at: Date.now() - 3_600_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar
  },
  {
    id: 33,
    type: 'note',
    content: '效果验收现场照片，主要模块功能已通过客户验收。',
    tags: [],
    images: [{ url: 'https://p1.itc.cn/images01/20220108/e8a62d7ce6d64ee9960552756ea7a019.jpeg' }],

    is_synced: false,
    created_at: Date.now() - 1_200_000,
    updated_at: Date.now() - 1_200_000,
    user: pickUser(2),
    user_id: pickUser(2).id,
    user_name: pickUser(2).name,
    user_avatar: pickUser(2).avatar
  },
  {
    id: 34,
    type: 'note',
    content: '展会现场随拍，客户对新功能兴趣浓厚，后续跟进演示。',
    tags: [],
    images: [
      { url: 'https://pic.rmb.bdstatic.com/bjh/news/b5a011d0f346d4274c0373d969b4eb59.png' },
      {
        url: 'https://images.unsplash.com/photo-1521737604893-d14cc237f11d?w=1200&q=80&auto=format&fit=crop'
      },
      {
        url: 'https://images.unsplash.com/photo-1519389950473-47ba0277781c?w=1200&q=80&auto=format&fit=crop'
      },
      {
        url: 'https://newbbs-fd.zol-img.com.cn/t_s800x5000/g5/M00/03/00/ChMkJ1fSWn-IHmiDAC4KLDMgyQcAAVJQAJuvd8ALgpE905.jpg'
      }
    ],

    is_synced: false,
    created_at: Date.now() - 1_800_000,
    updated_at: Date.now() - 1_800_000,
    user: pickUser(1),
    user_id: pickUser(1).id,
    user_name: pickUser(1).name,
    user_avatar: pickUser(1).avatar
  },
  {
    id: 35,
    type: 'note',
    content: '白板讨论方案（记录关键流程与接口）。',
    tags: [],
    images: [
      {
        url: 'https://images.unsplash.com/photo-1503676260728-1c00da094a0b?w=1200&q=80&auto=format&fit=crop'
      },
      {
        url: 'https://images.unsplash.com/photo-1557800636-894a64c1696f?w=1200&q=80&auto=format&fit=crop'
      }
    ],

    is_synced: false,
    created_at: Date.now() - 2_400_000,
    updated_at: Date.now() - 2_400_000,
    user: pickUser(3),
    user_id: pickUser(3).id,
    user_name: pickUser(3).name,
    user_avatar: pickUser(3).avatar
  },
  {
    id: 36,
    type: 'note',
    content: '客户提供的 UI 草图（初稿）。',
    tags: [],
    images: [
      { url: 'https://inews.gtimg.com/om_bt/OBcldFgmIx8oKc7VlrEnHqso_pEEeyfa9Va0gHrQR7NBcAA/641' },
      {
        url: 'https://images.unsplash.com/photo-1512295767273-ac109ac3acfa?w=1200&q=80&auto=format&fit=crop'
      },
      { url: 'https://pic.rmb.bdstatic.com/bjh/news/715ee409a56ff9c98b30e633c0e54ab2.png' },
      {
        url: 'https://images.unsplash.com/photo-1518779578993-ec3579fee39f?w=1200&q=80&auto=format&fit=crop'
      },
      {
        url: 'https://images.unsplash.com/photo-1522202176988-66273c2fd55f?w=1200&q=80&auto=format&fit=crop'
      },
      {
        url: 'https://images.unsplash.com/photo-1557800636-894a64c1696f?w=1200&q=80&auto=format&fit=crop'
      }
    ],

    is_synced: false,
    created_at: Date.now() - 3_000_000,
    updated_at: Date.now() - 3_000_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar
  },

  {
    id: 2,
    type: 'note',
    content:
      '讨论了2024年度合作计划，重点关注云计算和AI领域的合作机会。客户方表示对我们的产品很感兴趣，下周将安排技术团队进行深入交流。',
    company_id: 1001,
    company_name: '华为技术有限公司',
    tags: ['会议', '合作'],

    is_synced: false,
    like_count: 0,
    comment_count: 1,
    created_at: Date.now() - 7_200_000,
    updated_at: Date.now() - 7_200_000,
    user: pickUser(1),
    user_id: pickUser(1).id,
    user_name: pickUser(1).name,
    user_avatar: pickUser(1).avatar
  },
  {
    id: 8,
    type: 'event',
    content:
      '新产品发布会将在下周三举行，届时将展示我们最新的CRM系统功能。请所有团队成员准时参加，并准备好演示材料。参与方：{[@王五,3]}，联系人：{[#张伟,2001,1004]}，公司：{[$阿里巴巴集团,1004]}。',
    tags: [],

    is_synced: false,
    created_at: Date.now() - 7_400_000,
    updated_at: Date.now() - 7_400_000,
    user: pickUser(2),
    user_id: pickUser(2).id,
    user_name: pickUser(2).name,
    user_avatar: pickUser(2).avatar,
    event_start_time: Date.now() + 604_800_000, // 一周后
    event_end_time: Date.now() + 604_800_000 + 7_200_000, // 2小时后结束
    event_location: '北京国际会议中心 3号厅',
    event_attendees: ['张三', '李四', '王五', '赵六'],
    event_attendee_users: [pickUser(0), pickUser(1), pickUser(2), pickUser(3)]
  },
  {
    id: 3,
    type: 'note',
    content:
      '张经理对我们的解决方案表示认可，提出了一些定制化需求。需要在下周三之前提供详细的技术方案和报价。',
    contact_id: 2001,
    contact_name: '张伟 - 采购经理',
    company_name: '阿里巴巴集团',
    tags: [],

    is_synced: false,
    like_count: 5,
    comment_count: 0,
    created_at: Date.now() - 86_400_000,
    updated_at: Date.now() - 86_400_000,
    user: pickUser(2),
    user_id: pickUser(2).id,
    user_name: pickUser(2).name,
    user_avatar: pickUser(2).avatar
  },
  {
    id: 4,
    type: 'email',
    content:
      '腾讯云团队发来合作意向邮件，希望在企业服务领域展开合作。邮件中提到了具体的合作模式和预期目标，需要尽快回复。相关：{[@张三,1]}、{[#李明,2002,1005]}、{[$百度在线,1005]}。',
    company_name: '腾讯科技',
    tags: ['rfq'],
    attachments: ['合作意向书.pdf', '产品介绍.pptx'],

    is_synced: false,
    created_at: Date.now() - 172_800_000,
    updated_at: Date.now() - 172_800_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar,
    from: 'partner@tencent.com',
    to: ['me@example.com'],
    subject: 'Re: 企业服务合作意向',
    cc: ['team@tencent.com'],
    from_user: { ...pickExt(0), email: 'partner@tencent.com' },
    to_users: [pickUser(0)],
    is_outbound: false
  },
  {
    id: 5,
    type: 'note',
    content:
      '参加了字节跳动组织的技术交流会，了解到他们在AI和大数据方面的最新进展。会后与技术负责人进行了深入交流，探讨了潜在的合作机会。',
    company_id: 1002,
    company_name: '字节跳动',
    tags: [],

    is_synced: false,
    like_count: 1,
    comment_count: 2,
    created_at: Date.now() - 259_200_000,
    updated_at: Date.now() - 259_200_000,
    user: pickUser(3),
    user_id: pickUser(3).id,
    user_name: pickUser(3).name,
    user_avatar: pickUser(3).avatar
  },
  {
    id: 6,
    type: 'note',
    content:
      '与李总监确认了项目需求，主要包括：1. 系统集成方案 2. 数据迁移计划 3. 培训安排。预计项目周期为3个月。',
    contact_id: 2002,
    contact_name: '李明 - 技术总监',
    company_name: '百度在线',
    tags: [],

    is_synced: false,
    created_at: Date.now() - 345_600_000,
    updated_at: Date.now() - 345_600_000,
    user: pickUser(1),
    user_id: pickUser(1).id,
    user_name: pickUser(1).name,
    user_avatar: pickUser(1).avatar
  },
  {
    id: 7,
    type: 'note',
    content:
      '1. 完成华为项目的技术方案\n2. 准备腾讯合作的回复邮件\n3. 跟进字节跳动的合作进展\n4. 安排百度项目的启动会议\n5. Token Demo: {[@李四,2]} | {[#张伟,2001,1004]} | {[$阿里巴巴集团,1004]}',
    tags: [],

    is_synced: false,
    like_count: 0,
    comment_count: 0,
    created_at: Date.now() - 432_000_000,
    updated_at: Date.now() - 432_000_000,
    user: pickUser(4),
    user_id: pickUser(4).id,
    user_name: pickUser(4).name,
    user_avatar: pickUser(4).avatar
  },

  {
    id: 9,
    type: 'email',
    content:
      '收到客户对上个月交付项目的反馈，整体满意度较高，但提出了一些优化建议。需要整理成改进计划并在下次会议中讨论。',
    tags: ['replied'],

    is_synced: false,
    created_at: Date.now() - 604_800_000,
    updated_at: Date.now() - 604_800_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar,
    from: 'client@company.com',
    to: ['me@example.com'],
    subject: '项目反馈 - 12月交付',
    cc: ['manager@company.com'],
    from_user: { ...pickExt(1), email: 'client@company.com' },
    to_users: [pickUser(0)],
    is_outbound: false
  },
  {
    id: 10,
    type: 'event',
    content:
      '公司组织的季度团队建设活动，地点在郊外度假村。活动包括户外拓展、团队游戏和晚宴。请大家提前安排好工作，准时参加。',
    tags: [],

    is_synced: false,
    created_at: Date.now() - 691_200_000,
    updated_at: Date.now() - 691_200_000,
    user: pickUser(3),
    user_id: pickUser(3).id,
    user_name: pickUser(3).name,
    user_avatar: pickUser(3).avatar,
    event_start_time: Date.now() + 1_209_600_000, // 两周后
    event_end_time: Date.now() + 1_209_600_000 + 28_800_000, // 8小时后结束
    event_location: '阳光度假村',
    event_attendees: ['全体员工'],
    event_attendee_users: [pickUser(1), pickUser(3)]
  },
  {
    id: 11,
    type: 'note',
    content:
      '为小米科技团队进行了产品演示，展示了我们CRM系统的核心功能和优势。小米团队对系统的易用性和功能完整性表示认可，计划下周进行试用。',
    company_id: 1003,
    company_name: '小米科技',
    tags: [],

    is_synced: false,
    like_count: 7,
    comment_count: 4,
    created_at: Date.now() - 777_600_000,
    updated_at: Date.now() - 777_600_000,
    user: pickUser(4),
    user_id: pickUser(4).id,
    user_name: pickUser(4).name,
    user_avatar: pickUser(4).avatar
  },
  {
    id: 12,
    type: 'email',
    content: '我们已向客户发送了项目方案与报价，等待李娜确认下一步。',
    tags: [],

    is_synced: false,
    created_at: Date.now() - 100_000_000,
    updated_at: Date.now() - 100_000_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar,

    from: 'me@example.com',
    to: ['client@company.com'],
    subject: '项目方案与报价',
    cc: ['sales@acme.com'],
    from_user: pickUser(0),
    to_users: [{ ...pickExt(1), email: 'client@company.com' }],

    is_outbound: true
  },
  {
    id: 13,
    type: 'linkedin',
    content: '通过 LinkedIn 与客户关键人建立连接，并发送了首次跟进消息。',
    tags: [],
    is_synced: false,
    created_at: Date.now() - 200_000_000,
    updated_at: Date.now() - 200_000_000,
    user: pickUser(2),
    user_id: pickUser(2).id,
    user_name: pickUser(2).name,
    user_avatar: pickUser(2).avatar,
    from_user: pickUser(2),
    to_users: [pickExt(1)],
    is_outbound: true
  },
  {
    id: 14,
    type: 'facebook',
    content: 'Facebook 私信收到客户咨询，已回复演示链接与报价说明。',
    tags: [],
    is_synced: false,
    created_at: Date.now() - 190_000_000,
    updated_at: Date.now() - 190_000_000,
    user: pickUser(1),
    user_id: pickUser(1).id,
    user_name: pickUser(1).name,
    user_avatar: pickUser(1).avatar,
    from_user: pickExt(2),
    to_users: [pickUser(1)],
    is_outbound: false
  },
  {
    id: 15,
    type: 'x',
    content: '在 X（Twitter）上与潜在客户互动，分享了成功案例与技术文章。',
    tags: [],
    is_synced: false,
    created_at: Date.now() - 180_000_000,
    updated_at: Date.now() - 180_000_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar,
    from_user: pickUser(0),
    to_users: [pickExt(5)],
    is_outbound: true
  },
  {
    id: 16,
    type: 'wechat',
    content: '微信中确认了技术评审时间，赵磊需要我们准备接口清单与测试账号。',
    tags: ['tech_talk'],
    is_synced: false,
    created_at: Date.now() - 170_000_000,
    updated_at: Date.now() - 170_000_000,
    user: pickUser(3),
    user_id: pickUser(3).id,
    user_name: pickUser(3).name,
    user_avatar: pickUser(3).avatar,
    from_user: pickExt(3),
    to_users: [pickUser(3)],
    is_outbound: false
  },
  {
    id: 17,
    type: 'phone',
    content: '电话沟通确认需求范围与交付节奏，初步定于下周启动。',
    tags: [],
    is_synced: false,
    created_at: Date.now() - 160_000_000,
    updated_at: Date.now() - 160_000_000,
    user: pickUser(4),
    user_id: pickUser(4).id,
    user_name: pickUser(4).name,
    user_avatar: pickUser(4).avatar,
    from_user: pickUser(4),
    to_users: [pickExt(7)],
    is_outbound: true
  },
  {
    id: 18,
    type: 'qq',
    content: 'QQ 群里同步了版本更新日志，客户反馈登录体验显著改善。',
    tags: [],
    is_synced: false,
    created_at: Date.now() - 150_000_000,
    updated_at: Date.now() - 150_000_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar,
    from_user: pickUser(0),
    to_users: [pickExt(6)],
    is_outbound: true
  },
  {
    id: 19,
    type: 'skype',
    content: 'Skype 远程会议讨论了数据迁移方案，明确了字段映射与校验规则。',
    tags: ['tac_support'],
    is_synced: false,
    created_at: Date.now() - 140_000_000,
    updated_at: Date.now() - 140_000_000,
    user: pickUser(1),
    user_id: pickUser(1).id,
    user_name: pickUser(1).name,
    user_avatar: pickUser(1).avatar,
    from_user: pickExt(9),
    to_users: [pickUser(1)],
    is_outbound: false
  },
  {
    id: 20,
    type: 'telegram',
    content: 'Telegram 群收到客户的安全合规问题，已同步相关白皮书与明细。',
    tags: ['Telegram'],
    is_synced: false,
    created_at: Date.now() - 130_000_000,
    updated_at: Date.now() - 130_000_000,
    user: pickUser(2),
    user_id: pickUser(2).id,
    user_name: pickUser(2).name,
    user_avatar: pickUser(2).avatar,
    from_user: pickUser(2),
    to_users: [pickExt(8)],
    is_outbound: true
  },
  {
    id: 21,
    type: 'icq',
    content: 'ICQ 私聊确认了 POC 环境的访问方式与测试用例范围。',
    tags: ['tech_talk'],
    is_synced: false,
    created_at: Date.now() - 120_000_000,
    updated_at: Date.now() - 120_000_000,
    user: pickUser(3),
    user_id: pickUser(3).id,
    user_name: pickUser(3).name,
    user_avatar: pickUser(3).avatar,
    from_user: pickExt(4),
    to_users: [pickUser(3)],
    is_outbound: false
  },
  {
    id: 22,
    type: 'whatsapp',
    content: 'WhatsApp 确认预计合同签署时间，法务正在走流程。',
    tags: ['WhatsApp'],
    is_synced: false,
    created_at: Date.now() - 110_000_000,
    updated_at: Date.now() - 110_000_000,
    user: pickUser(4),
    user_id: pickUser(4).id,
    user_name: pickUser(4).name,
    user_avatar: pickUser(4).avatar,
    from_user: pickUser(4),
    to_users: [pickExt(0)],
    is_outbound: true
  },
  {
    id: 23,
    type: 'line',
    content: 'LINE 上收集到用户反馈：移动端筛选条件记忆能力需要增强。',
    tags: ['社交', 'replied'],
    is_synced: false,
    created_at: Date.now() - 100_000_000,
    updated_at: Date.now() - 100_000_000,
    user: pickUser(1),
    user_id: pickUser(1).id,
    user_name: pickUser(1).name,
    user_avatar: pickUser(1).avatar,
    from_user: pickExt(2),
    to_users: [pickUser(1)],
    is_outbound: false
  },
  {
    id: 24,
    type: 'inperson',
    content: '与客户在咖啡厅进行面对面沟通，确认了实施里程碑与双方职责分工。',
    tags: [],
    is_synced: false,
    created_at: Date.now() - 95_000_000,
    updated_at: Date.now() - 95_000_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar,
    from_user: pickUser(0),
    to_users: [pickExt(6)],
    is_outbound: true
  },
  {
    id: 25,
    type: 'inperson',
    content: '客户来访，现场对接技术问题并完成接口联调演示。',
    tags: ['f2f_meeting'],
    is_synced: false,
    created_at: Date.now() - 85_000_000,
    updated_at: Date.now() - 85_000_000,
    user: pickUser(2),
    user_id: pickUser(2).id,
    user_name: pickUser(2).name,
    user_avatar: pickUser(2).avatar,
    from_user: pickExt(5),
    to_users: [pickUser(2)],
    is_outbound: false
  },
  {
    id: 26,
    type: 'linkedin',
    content: '客户在 LinkedIn 点赞了我们的产品更新动态。',
    tags: ['liked'],

    is_synced: false,
    created_at: Date.now() - 60_000_000,
    updated_at: Date.now() - 60_000_000,
    user: pickUser(2),
    user_id: pickUser(2).id,
    user_name: pickUser(2).name,
    user_avatar: pickUser(2).avatar,
    from_user: pickExt(7),
    to_users: [pickUser(2)],
    is_outbound: false
  },
  {
    id: 27,
    type: 'linkedin',
    content: '客户在 LinkedIn 分享了我们的白皮书内容。',
    tags: ['shared'],

    is_synced: false,
    created_at: Date.now() - 58_000_000,
    updated_at: Date.now() - 58_000_000,
    user: pickUser(1),
    user_id: pickUser(1).id,
    user_name: pickUser(1).name,
    user_avatar: pickUser(1).avatar,
    from_user: pickExt(6),
    to_users: [pickUser(1)],
    is_outbound: false
  },
  {
    id: 28,
    type: 'email',
    content: '客户查看了我们发送的内容（邮件已读、访问页面或下载资料）。',
    tags: [],

    is_synced: false,
    created_at: Date.now() - 56_000_000,
    updated_at: Date.now() - 56_000_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar,
    subject: '已读回执: 方案资料',
    from_user: pickExt(5),
    to_users: [pickUser(0)],
    is_outbound: false
  },
  {
    id: 29,
    type: 'wechat',
    content: '客户添加了我们为微信好友。',
    tags: ['friended'],

    is_synced: false,
    created_at: Date.now() - 54_000_000,
    updated_at: Date.now() - 54_000_000,
    user: pickUser(3),
    user_id: pickUser(3).id,
    user_name: pickUser(3).name,
    user_avatar: pickUser(3).avatar,
    from_user: pickExt(8),
    to_users: [pickUser(3)],
    is_outbound: false
  },
  {
    id: 30,
    type: 'email',
    content: '收到客户的 RFP（招标/方案请求），请准备技术与商务方案。',
    tags: ['rfp'],

    is_synced: false,
    created_at: Date.now() - 52_000_000,
    updated_at: Date.now() - 52_000_000,
    user: pickUser(4),
    user_id: pickUser(4).id,
    user_name: pickUser(4).name,
    user_avatar: pickUser(4).avatar,
    subject: 'RFP 请求',
    from_user: pickExt(2),
    to_users: [pickUser(4)],
    is_outbound: false
  },
  {
    id: 31,
    type: 'email',
    content: '客户确认进入报价→成交流程，请准备合同与交付计划。',
    tags: ['qtt'],

    is_synced: false,
    created_at: Date.now() - 50_000_000,
    updated_at: Date.now() - 50_000_000,
    user: pickUser(1),
    user_id: pickUser(1).id,
    user_name: pickUser(1).name,
    user_avatar: pickUser(1).avatar,
    subject: 'QTT 阶段确认',
    from_user: pickExt(9),
    to_users: [pickUser(1)],
    is_outbound: false
  },
  {
    id: 32,
    type: 'email',
    content: '客户由第三方推荐而来，请优先跟进。',
    tags: ['recommended'],

    is_synced: false,
    created_at: Date.now() - 48_000_000,
    updated_at: Date.now() - 48_000_000,
    user: pickUser(0),
    user_id: pickUser(0).id,
    user_name: pickUser(0).name,
    user_avatar: pickUser(0).avatar,
    subject: '推荐客户对接',
    from_user: pickExt(0),
    to_users: [pickUser(0)],
    is_outbound: false
  }
]

/**
 * 笔记服务类
 */
export class NoteService {
  /**
   * 模拟网络延迟
   */
  private async delay(ms = 300): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  /**
   * 查询笔记列表
   */
  async queryNotes(params: QueryNoteParams = {}): Promise<Note[]> {
    await this.delay()

    let filtered = [...mockNotes]

    // 按简化类别筛选（UI）
    if (params.category) {
      switch (params.category) {
        case 'note': {
          filtered = filtered.filter(n => n.type === 'note')

          break
        }
        case 'mail': {
          filtered = filtered.filter(n => n.type === 'email')

          break
        }
        case 'calendar': {
          filtered = filtered.filter(n => n.type === 'event')

          break
        }

        // No default
      }
    }

    // 按类型筛选
    if (params.type) {
      filtered = filtered.filter(n => n.type === params.type)
    }

    // 按参与人筛选（from_user / to_users），兼容旧 contact_id
    if (params.contact_id != null) {
      const target = params.contact_id
      filtered = filtered.filter(n => {
        const inFrom = n.from_user?.id === target
        const inTo = Array.isArray(n.to_users) && n.to_users.some(u => u?.id === target)
        const inLegacyContact = typeof n.contact_id === 'number' && n.contact_id === target
        return inFrom || inTo || inLegacyContact
      })
    }

    // 关键词搜索
    if (params.keyword) {
      const keyword = params.keyword.toLowerCase()
      filtered = filtered.filter(
        n => n.title?.toLowerCase().includes(keyword) || n.content.toLowerCase().includes(keyword)
      )
    }

    // 时间范围（创建时间）
    if (params.created_at_from != null) {
      filtered = filtered.filter(n => n.created_at >= params.created_at_from!)
    }
    if (params.created_at_to != null) {
      filtered = filtered.filter(n => n.created_at <= params.created_at_to!)
    }

    // 排序
    const orderBy = params.order_by || 'created_at'
    const isDesc = params.order_direction !== 'asc'

    filtered.sort((a, b) => {
      const aVal = a[orderBy]
      const bVal = b[orderBy]
      return isDesc ? bVal - aVal : aVal - bVal
    })

    // 分页
    const offset = params.offset || 0
    const limit = params.limit || 20

    return filtered.slice(offset, offset + limit)
  }

  /**
   * 统计各类型数量（忽略 category/type 筛选，应用关键词与时间范围）
   */
  async getTypeCounts(
    params: QueryNoteParams = {}
  ): Promise<Array<{ type: Note['type']; count: number }>> {
    await this.delay(0)

    // 基于 mockNotes 应用关键词与时间范围
    let filtered = [...mockNotes]

    // 关键词
    if (params.keyword) {
      const keyword = params.keyword.toLowerCase()
      filtered = filtered.filter(
        n => n.title?.toLowerCase().includes(keyword) || n.content.toLowerCase().includes(keyword)
      )
    }

    // 时间范围（创建时间）
    if (params.created_at_from != null) {
      filtered = filtered.filter(n => n.created_at >= params.created_at_from!)
    }
    if (params.created_at_to != null) {
      filtered = filtered.filter(n => n.created_at <= params.created_at_to!)
    }

    // 按参与人筛选（from_user / to_users），兼容旧 contact_id
    if (params.contact_id != null) {
      const target = params.contact_id
      filtered = filtered.filter(n => {
        const inFrom = n.from_user?.id === target
        const inTo = Array.isArray(n.to_users) && n.to_users.some(u => u?.id === target)
        const inLegacyContact = typeof n.contact_id === 'number' && n.contact_id === target
        return inFrom || inTo || inLegacyContact
      })
    }

    const map = new Map<Note['type'], number>()
    for (const n of filtered) {
      map.set(n.type, (map.get(n.type) || 0) + 1)
    }

    // 只返回存在的类型（count > 0），按 count 降序
    return Array.from(map.entries())
      .map(([type, count]) => ({ type, count }))
      .sort((a, b) => b.count - a.count)
  }

  /** 列出当前筛选条件下存在记录的联系人（用于左侧 v-autocomplete） */
  async listContacts(params: QueryNoteParams = {}): Promise<Array<{ id: number; name: string }>> {
    await this.delay(0)

    // 基于 mockNotes 与传入条件筛选（关键词/时间范围/类型）
    let filtered = [...mockNotes]

    if (params.keyword) {
      const keyword = params.keyword.toLowerCase()
      filtered = filtered.filter(
        n => n.title?.toLowerCase().includes(keyword) || n.content.toLowerCase().includes(keyword)
      )
    }

    if (params.created_at_from != null) {
      filtered = filtered.filter(n => n.created_at >= params.created_at_from!)
    }
    if (params.created_at_to != null) {
      filtered = filtered.filter(n => n.created_at <= params.created_at_to!)
    }

    if (params.type) {
      filtered = filtered.filter(n => n.type === params.type)
    }

    const map = new Map<number, string>()
    for (const n of filtered) {
      // 参与者：发件人/对话发起人
      if (n.from_user?.id != null && n.from_user.name) {
        map.set(n.from_user.id, n.from_user.name)
      }
      // 参与者：收件人/对话对象
      if (Array.isArray(n.to_users)) {
        for (const u of n.to_users) {
          if (u?.id != null && u.name) map.set(u.id, u.name)
        }
      }
      // 兼容旧数据：基于 contact_id/contact_name
      if (n.contact_id != null && n.contact_name) {
        map.set(n.contact_id, n.contact_name)
      }
    }

    const contacts = Array.from(map.entries()).map(([id, name]) => ({ id, name }))
    contacts.sort((a, b) => a.name.localeCompare(b.name))
    return contacts
  }

  /**
   * 创建笔记
   */
  async createNote(input: CreateNoteInput): Promise<Note> {
    await this.delay()

    const newNote: Note = {
      id: Date.now(),
      ...input,

      is_synced: false,
      created_at: Date.now(),
      updated_at: Date.now()
    }

    mockNotes.unshift(newNote)
    return newNote
  }

  /**
   * 更新笔记
   */
  async updateNote(input: UpdateNoteInput): Promise<Note | null> {
    await this.delay()

    const index = mockNotes.findIndex(n => n.id === input.id)
    if (index === -1) return null

    const existing = mockNotes[index]!
    const updated: Note = {
      ...existing,
      ...input,
      updated_at: Date.now()
    }

    mockNotes[index] = updated
    return updated
  }

  /**
   * 删除笔记
   */
  async deleteNote(id: number): Promise<boolean> {
    await this.delay()

    const index = mockNotes.findIndex(n => n.id === id)
    if (index === -1) return false

    mockNotes.splice(index, 1)
    return true
  }
}

/**
 * 导出单例
 */
export const noteService = new NoteService()

/**
 * 后续切换到真实 API 时的示例：
 *
 * import { ajax } from '@/ajax/ajax'
 *
 * export class NoteService {
 *   async queryNotes(params: QueryNoteParams = {}): Promise<Note[]> {
 *     const response = await ajax.get('/api/notes', { params })
 *     return response.data.data
 *   }
 *
 *   async createNote(input: CreateNoteInput): Promise<Note> {
 *     const response = await ajax.post('/api/notes', input)
 *     return response.data.data
 *   }
 *
 *   // ... 其他方法
 * }
 */
